Ext.onReady(function(){
	//搜索栏
Ext.ns('Ext.ux.form');
Ext.ux.form.SearchField = Ext.extend(Ext.form.TwinTriggerField, {
    initComponent : function(){
        Ext.ux.form.SearchField.superclass.initComponent.call(this);
        this.on('specialkey', function(f, e){
            if(e.getKey() == e.ENTER){
                this.onTrigger2Click();
            }
        }, this);
    },

    validationEvent:false,
    validateOnBlur:false,
    trigger1Class:'x-form-clear-trigger',
    trigger2Class:'x-form-search-trigger',
    hideTrigger1:true,
    width:180,
    hasSearch : false,
    paramName : 'query',
    onTrigger1Click : function(){
        if(this.hasSearch){
            this.el.dom.value = '';
            var o = {start: 0};
            this.store.baseParams = this.store.baseParams || {};
            this.store.baseParams[this.paramName] = '';
            this.store.reload({
				params: {
					start: 0,
					limit: 7
				}
			});
            this.triggers[0].hide();
            this.hasSearch = false;
        }
    },

    onTrigger2Click : function(){
        var v = this.getRawValue();	
        if(v.length < 1){
            this.onTrigger1Click();
            return;
        }
        var o = {start: 0};
        this.store.baseParams = this.store.baseParams || {};
        this.store.baseParams[this.paramName] = v;
        this.hasSearch = true;
        this.triggers[0].show();
		this.store.filter('name',v);
}
});
//搜索栏定义结束


	var sheetlist = '';//设置一个变量用来装载表单数据
	var sheetnum  = new Array(); //设置一个数组用来保存选择的外卖个数
	var store = new Ext.data.Store({
		proxy: new Ext.ux.data.PagingMemoryProxy(data),
		reader: new Ext.data.ArrayReader({
			record: 'list',
			id: 'Id',
			totalRecords: '@total'
		}, [{
			name: 'Id'
		}, {
			name: 'name'
		}, {
			name: 'riceprice',
			type: 'float'
		},{
			name: 'price',
			type: 'float'
		}, {
			name: 'bprice',
			type: 'float'
		}, {
			name: 'shop'
		}, {
			name: 'school'
		}, {
			name: 'content'
		},{
			name: 'kind'
		},{
			name: 'score'
		}])
	});
	
	    function chMoney(val){
            return '<span style="color:red;">' + val + '￥</span>';
    }

	    function dishImage(value){
        return String.format(
                '<b></b><img src="images/dish/{0}.jpg" width="60" height="40">',
                value);
    }	
	
	    function onDelete() {
        var rec = secondGrid.getSelectionModel().getSelected();
        if (!rec) {
            return false;
        }
        secondGrid.store.remove(rec);
    }

//Grid1
    grid = new Ext.grid.GridPanel({
        store: store,
		ddGroup          : 'secondGridDDGroup',
		enableDragDrop   : true,
		ddText :'选择了一道菜',
		autoExpandColumn : 'name',
		loadMask         : true,
        columns: [
            {header: "名称", width: 180, dataIndex: 'name', sortable: true},
            {header: "单价", width: 80,renderer:chMoney, dataIndex: 'price', sortable: true},
            {header: "餐馆", width: 115, dataIndex: 'shop', sortable: true},
            {header: "图片", width: 100, dataIndex: 'Id',renderer:dishImage, sortable: false}
        ],
		sm: new Ext.grid.RowSelectionModel({singleSelect: true}),
		viewConfig: {
			forceFit: true,
                sortAscText :'正序',
                sortDescText :'倒序',
                columnsText:'列显示/隐藏',
                groupByText:'依本列分组',
                showGroupsText:'分组显示',
                groupTextTpl: '{text} ({[values.rs.length]} 条记录)'
		},
        
		split: true,
		region: 'east'
    });
	
//点击后弹出的关于菜品的详细介绍	
	var contentTplMarkup = [
		'<img src="images/dish/{Id}.jpg" width="230" height="150">',
		'菜名: <b>{name}</b><br/>',
		'提供餐馆: {shop}<br/>',
		'评分等级: <div id="starrat" style="display:none"><ul class="star-rating"><li><a id="tip1"  href="#" target="blank" class="one-star" onclick="star()">1</a></li><li><a id="tip2"  href="starrat.php?num=2" class="two-stars">2</a></li>  <li><a id="tip3"  href="#" class="three-stars">3</a></li>  <li><a id="tip4"  href="#" class="four-stars">4</a></li> <li><a id="tip5"  href="#" class="five-stars">5</a></li></ul></div><div id="starratshow" onmouseover="showStarTips()" onclick="starRat()"><img src="images/icon/star{score}.gif" title="点击开始评分"></div>'
	];
	var contentTpl = new Ext.Template(contentTplMarkup);
    var secondGridStore = new Ext.data.JsonStore({
        fields : [
	   {name: 'name', mapping : 'name'},
	   {name: 'sheetnum', mapping : 'sheetnum'},
	   {name: 'sheetprice', mapping : 'sheetprice'},
	   {name: 'column2', mapping : 'column2'}
	],
		root   : 'records'
    });
//Grid2点菜单
    var secondGrid = new Ext.grid.EditorGridPanel({
		selModel: new Ext.grid.RowSelectionModel(),
		ddGroup          : 'grid',
        store            : secondGridStore,
		sortInfo: {field: 'due', direction: 'ASC'},
        columns          : [
		{
			id: 'sheetid',
			hidden: true,
			dataIndex: 'Id',
			renderer: function(v){
			}
		},
		{ id : 'sheetname', header: "名称", width: 160, sortable: true, dataIndex: 'name'},
		{ id : 'sheetnum',  header: "数量", width: 50 , type	: 'float',dataIndex: 'sheetnum',editor:new Ext.grid.GridEditor(new Ext.form.TextField({allowBlank:false,maxLength:2,vtype:'alphanum'})),sortable: true,renderer : function(value, metadata, record, rowIndex, colIndex, store){
						var obj = record.data;  
						if (value == null) {
							sheetnum[obj.Id]=1;
							return 1;
						}else{
							sheetnum[obj.Id]=value;
							return value;
						} ;
                }
            },
		{ id : 'sheetprice', header: "价格", type: 'float', width: 50, sortable: true, dataIndex: 'sheetprice',renderer : function(value, metadata, record, rowIndex, colIndex, store) {  
                 var obj = record.data;  
				 if (obj.sheetnum == null) {
				 	return obj.price;
				 }
				 else {
				 	//sheetlist = obj.name+'：'+obj.sheetnum+"份；共计"+(obj.sheetnum * obj.price);
					//sheetnum = obj.sheetnum;
				 	return obj.price*obj.sheetnum;
				 } 
            }  
		}
	],
        stripeRows       : true,
        autoExpandColumn : 'sheetname',
        width            : 325,
		height			 : 400,
		region           : 'center',
        title            : '我的点菜单',
		bbar    : 
		[{
            text: '删除',
            iconCls: 'k-button-delsole',
            handler: onDelete
        }, '-', // Fill
			{
				text    : '全部删除',
				iconCls : 'k-button-delall',
				handler : function() {
					secondGridStore.removeAll();
				}
			},'-',
			{
				text    : '提交',
				iconCls : 'k-button-submit',
				handler : function(value,record,grid, rowIndex, columnIndex, e) {
		var s = secondGrid.getStore();
		var i = secondGridStore.data.items.length;
		var sheetsum = 0;
		for (n = 0; n < i; n++) {
			
			sheetsum = sheetsum+s.getAt(n).get('price')*sheetnum[s.getAt(n).get('Id')];
			sheetlist = sheetlist + s.getAt(n).get('name') +'：'+sheetnum[s.getAt(n).get('Id')]+'个；<br>';
			//alert(x.get('name') + x.get('price'));
		}
		sheetlist = sheetlist +'共计'+sheetsum + '元';
		Ext.Ajax.request({
			url	    : 'book.php',
			success : function(result,request) {
				Ext.MessageBox.alert('订餐成功','您订购了: ' + result.responseText);
				sheetlist = '';
				secondGridStore.removeAll();
			},
			failure: function ( result, request) { 
				Ext.MessageBox.alert('提交失败', result.responseText); 
			},
		   headers: {
		       'my-header': 'foo'
		   },
		   params: {foo : sheetlist}});
			}}
		]
		
});
//Grid2点菜单结束


	var ct = new Ext.Panel({
		renderTo: 'mainDiv',
		frame: true,
		split: true,
		collapsible: true,
		width: 740,
		height: 430,
		layout: 'border',
		items: [
			grid,
			{
				id: 'detailPanel',
				region: 'center',
				bodyStyle: {
					background: '#ffffff',
					padding: '7px'
				},
				html: '选择查看详情.'
			}
		],
			bbar: new Ext.PagingToolbar({
            pageSize: 7,
            store: store,
            displayInfo: true,
			beforePageText:'页数',
			afterPageText :'共{0}',
			emptyMsg	  :'没有您要查找的外卖，请更改查询条件',
			displayMsg:"显示第 {0} - {1} 共有 {2}种外卖",
            plugins: new Ext.ux.ProgressBarPager()
        }),
			tbar: [
			{
            text: '打开点菜单',
            iconCls: 'k-button-book',
			handler: showsheet
        },
			new Ext.ux.form.SearchField({
                store: store,
                width:320
				
		}),{
			text: '高级搜索',
            iconCls: 'k-button-book',
			handler: search
		},{
			text: '学校切换:西南民族大学',
			handler: function (){
				grid.store.filter('name','牛肉堡')
			}
		}
]
	})
	grid.getSelectionModel().on('rowselect', function(sm, rowIdx, r) {
		var detailPanel = Ext.getCmp('detailPanel');
		contentTpl.overwrite(detailPanel.body, r.data);
	});
    //store.load();
	store.load({params:{start:0, limit:7}});
	secondGrid.render('panel');
	secondGrid.hide();

//win1点菜页面窗口
	var win = new Ext.Window({
	el: 'panel',
	width: 338,
	resizable:false,
	height: 430,
	maximizable: true,
	closeAction: 'hide',
	items: [secondGrid]
});
	function showsheet(){
		secondGrid.show();
		win.show();
	};

//点菜页面结束


//高级搜索页面
    var form = new Ext.form.FormPanel({
        baseCls: 'x-plain',
        labelWidth: 55,
        defaultType: 'textfield',
		standardSubmit: true, 
        items: [{
			id : 'listsearch',
            fieldLabel: 'Send To',
            name: 'listsearch',
            anchor:'100%'  // anchor width by percentage
        }],
		
		        buttons: [{
			text: 'Send',
			handler: function(){
				form.getForm().getEl().dom.action = 'search.php';
				form.getForm().getEl().dom.method = 'POST';
				form.getForm().submit();
			}
		},{
            text: 'Cancel'
        }]
    });

	var search = new Ext.Window({
	el: 'search',
	width: 338,
	resizable:false,
	height: 430,
	maximizable: true,
	closeAction: 'hide',
        items: form



});
	search.hide();
	
	
		function search(){
		search.show();
	};
	
//高级搜索结束	


	var firstGridDropTargetEl =  grid.getView().el.dom.childNodes[0].childNodes[1];
	var firstGridDropTarget = new Ext.dd.DropTarget(firstGridDropTargetEl, {
		ddGroup    : 'firstGridDDGroup',
		copy       : true,
		notifyDrop : function(ddSource, e, data){

			// Generic function to add records.
			function addRow(record, index, allItems) {

				// Search for duplicates
				var foundItem = firstGridStore.findExact('name', record.data.name);
				// if not found
				if (foundItem  == -1) {
					firstGridStore.add(record);

					// Call a sort dynamically
					firstGridStore.sort('name', 'ASC');

					//Remove Record from the source
					ddSource.grid.store.remove(record);
				}
			}

			// Loop through the selections
			Ext.each(ddSource.dragData.selections ,addRow);
			return(true);
		}
	});


	// This will make sure we only drop to the view container
	var secondGridDropTargetEl = secondGrid.getView().el.dom.childNodes[0].childNodes[1]

	var destGridDropTarget = new Ext.dd.DropTarget(secondGridDropTargetEl, {
		ddGroup    : 'secondGridDDGroup',
		copy       : false,
		notifyDrop : function(ddSource, e, data){

			// Generic function to add records.
			function addRow(record, index, allItems) {

				// Search for duplicates
				var foundItem = secondGridStore.findExact('name', record.data.name);
				// if not found
				if (foundItem  == -1) {
					secondGridStore.add(record);
					// Call a sort dynamically
					secondGridStore.sort('name', 'ASC');

					//拖动之后是否删除
					//ddSource.grid.store.remove(record);
				}
			}
			// Loop through the selections
			Ext.each(ddSource.dragData.selections ,addRow);
			return(true);
		}
	});

});
	
